package com.qf.flower_service.service.impl;

import com.qf.flower_service.dao.FlowersDao;
import com.qf.flower_service.dao.mapper.FlowerTypeDetailMapper;
import com.qf.flower_service.dao.mapper.FlowersMapper;
import com.qf.flower_service.entity.FlowerTypeDetail;
import com.qf.flower_service.entity.Flowers;
import com.qf.flower_service.service.FlowersService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class FlowersServiceImpl implements FlowersService {
    @Autowired
    private FlowersDao flowersDao;

    @Autowired
    private FlowersMapper flowersMapper;

    @Autowired
    private FlowerTypeDetailMapper flowerTypeDetailMapper;


    @Override
    public List<Flowers> findBySubarea(String subarea) {
        if (StringUtils.isNotBlank(subarea)) {
            List<Flowers> flowers = flowersDao.findBySubarea(subarea);
            return flowers;
        }else {

            return null;
        }

    }

    @Override
    public List<Flowers> findByNameAndType(Long detailId, String flowerName) {
        List<Flowers> flowers = new ArrayList<>();
        if (detailId == null && StringUtils.isNotBlank(flowerName)) {
            //分类id为空名称不为空根据名称模糊查询
            flowers = flowersDao.findByFlowerNameLike(flowerName);
            return flowers;
        } else if (detailId != null && !StringUtils.isNotBlank(flowerName)) {
            //分类id不等于空名称为空根据分类查询
            Example example = new Example(FlowerTypeDetail.class);
            example.and().andEqualTo("detailId", detailId);
            List<FlowerTypeDetail> flowerTypeDetails = flowerTypeDetailMapper.selectByExample(example);
            for (FlowerTypeDetail flowerTypeDetail : flowerTypeDetails) {
                Long flowerId = flowerTypeDetail.getFlowerId();
                Flowers flower = flowersMapper.selectByPrimaryKey(flowerId);
                flowers.add(flower);

            }
            return flowers;
        } else if (detailId == null && !StringUtils.isNotBlank(flowerName)) {
            //id名称都为空查询所有
            flowers = flowersMapper.selectAll();
            return flowers;
        } else {
            //都不为空名称模糊查询再根据id查询
            flowerName = "%" + flowerName + "%";
            flowers = flowersMapper.findByDetailIdAndLinkFlowerName(detailId, flowerName);
            return flowers;
        }

    }

}
